<template>
  <div>
    <h2>我的预约</h2>
    <table>
      <thead>
        <tr>
          <th>课程</th>
          <th>周次</th>
          <th>日期</th>
          <th>节次</th>
          <th>实验室</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="appointment in mergedAppointments" :key="appointment.id">
          <td>{{ appointment.courseName }}</td>
          <td>{{ appointment.weekRange }}</td>
          <td>{{ getDayOfWeek(appointment.dayofweek) }}</td>
          <td>{{ appointment.section }}</td>
          <td>{{ appointment.labName }}</td>
        </tr>
      </tbody>
    </table>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  name: 'TeacherAppointments',
  data() {
    return {
      appointments: [], // 存储预约信息
      mergedAppointments: [], // 存储合并后的预约信息
      teacherId: '' // 指定教师的ID，即登录账号名
    };
  },
  created() {
    this.teacherId = localStorage.getItem('username');
    this.fetchAppointmentsByTeacherId(this.teacherId);
  },
  methods: {
    async fetchAppointmentsByTeacherId(teacherId) {
      try {
        const token = localStorage.getItem('token');
        const response = await axios.get(`http://192.168.129.76:8080/api/appointment_json/${teacherId}`, {
          headers: { 'Authorization': `Bearer ${token}` }
        });
        if (response.data.code === 200) {
          this.appointments = response.data.data;
          this.mergeAppointments();
        } else {
          console.error('获取预约信息失败，响应码：', response.data.code);
          alert('获取预约信息失败，请检查网络连接。');
        }
      } catch (error) {
        console.error('获取预约信息错误:', error);
        if (error.response && error.response.status !== 200) {
          alert('Token无效或已过期，请重新登录。');
        } else {
          alert('获取预约信息失败，请检查网络连接。');
        }
      }
    },
    mergeAppointments() {
      const mergedMap = new Map();
      this.appointments.forEach(appointment => {
        const key = `${appointment.courseName}-${appointment.labName}-${appointment.section}-${appointment.dayofweek}`;
        let merged = mergedMap.get(key);
        if (!merged) {
          merged = {
            courseId: appointment.courseId,
            courseName: appointment.courseName,
            labId: appointment.labId,
            labName: appointment.labName,
            section: appointment.section,
            dayofweek: appointment.dayofweek,
            weeks: [appointment.week],
            weekRange: `${appointment.week}`
          };
          mergedMap.set(key, merged);
        } else {
          merged.weeks.push(appointment.week);
        }
      });

      this.mergedAppointments = [];
      mergedMap.forEach(merged => {
        const sortedWeeks = merged.weeks.sort(((a, b) => a - b));
        let startWeek = sortedWeeks[0];
        let endWeek = sortedWeeks[sortedWeeks.length - 1];
        let currentWeek = startWeek;
        for (let i = 1; i < sortedWeeks.length; i++) {
          if (sortedWeeks[i] !== currentWeek + 1) {
            this.mergedAppointments.push({
              ...merged,
              weekRange: `${startWeek}-${currentWeek}`
            });
            startWeek = sortedWeeks[i];
          }
          currentWeek = sortedWeeks[i];
        }
        this.mergedAppointments.push({
          ...merged,
          weekRange: `${startWeek}-${endWeek}`
        });
      });
    },
    getDayOfWeek(dayofweek) {
      const days = ['星期一', '星期二', '星期三', '星期四', '星期五', '星期六', '星期日'];
      return days[dayofweek - 1] || '';
    }
  }
};
</script>

<style scoped>
table {
  width: 100%;
  max-width: 1200px;
  border-collapse: collapse;
  margin: 20px auto; /* 使表格居中并添加外边距 */
  font-family: Arial, sans-serif; /* 设置表格字体 */
}
th, td {
  border: 1px solid #cfe0ff;
  padding: 15px 60px;
  text-align: left;
}
thead {
  background-color: #d8e3f5; /* 设置表头背景颜色为蓝色 */
  color: rgb(127, 139, 192); /* 设置表头文本颜色为白色 */
}
td{
  background-color: #f3f7ff;
}
th {
  position: sticky; /* 使表头在滚动时固定 */
  top: 0; /* 表头固定在顶部 */
  z-index: 1; /* 确保表头在滚动时保持在最上层 */
}

</style>